package com.airbat.prize.modules.system.dal.redis.auth;

import com.airbat.prize.common.util.json.JsonUtils;
import com.airbat.prize.modules.system.service.auth.SysUserSessionService;
import com.airbat.prize.security.core.LoginUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.Duration;

import static com.airbat.prize.modules.system.dal.redis.SysRedisKeyConstants.LOGIN_USER;


/**
 * {@link LoginUser} 的 RedisDAO
 *
 * @author
 */
@Repository
public class SysLoginUserRedisDAO {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysUserSessionService sysUserSessionService;

    public LoginUser get(String sessionId) {
        String redisKey = formatKey(sessionId);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), LoginUser.class);
    }
    public void set(String sessionId, LoginUser loginUser) {
        String redisKey = formatKey(sessionId);
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(loginUser),
                Duration.ofMillis(sysUserSessionService.getSessionTimeoutMillis()));
    }
    public void set(String sessionId, String value) {
        String redisKey = sessionId;
        stringRedisTemplate.opsForValue().set(redisKey, value,
                Duration.ofMinutes(30l));
    }
    public String getString(String userName){
        return stringRedisTemplate.opsForValue().get(userName);
    }
    public void delete(String sessionId) {
        String redisKey = formatKey(sessionId);
        stringRedisTemplate.delete(redisKey);
    }

    private static String formatKey(String sessionId) {
        return String.format(LOGIN_USER.getKeyTemplate(), sessionId);
    }

}
